stages:          
  - build
  - builddocker
  - test
  # - deploy
  - deploy-compose

build-job:       
  tags:
    - local
  image: node:16.17
  stage: build
  script:
    - unset CI
    - npm install
    - npm run build
    - echo "build complete."
  artifacts:
    paths:
      - build

builddocker-job:
  tags: 
    - shell
  stage: builddocker
  before_script:
    - echo -n $CI_REGISTRY_PASSWORD | docker login -u $CI_REGISTRY_USER --password-stdin $CI_REGISTRY
  script:
    - docker build --pull -t "$CI_REGISTRY_IMAGE" .
    - docker image tag "$CI_REGISTRY_IMAGE" "$CI_REGISTRY_USER"/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHORT_SHA"
    - docker push "$CI_REGISTRY_USER"/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHORT_SHA"

localtest-job:
  tags:
    - shell
  stage: test
  script:
    - echo "Testing App lockaly in docker"
    - docker run --name it-guitarshop-test -p 80:80 -d "$CI_REGISTRY_USER"/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHORT_SHA"
    - wget http://localhost:80
    - cat index.html
    - rm index.html
    - docker stop it-guitarshop-test
    - docker rm it-guitarshop-test

# docker deploy#####

# deploy-job: 
#   tags:
#     - local
#   stage: deploy
#   before_script:
#     - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
#     - eval $(ssh-agent -s)
#     - echo "$SSH_KEY" | tr -d '\r' | ssh-add -
#     - mkdir -p ~/.ssh
#     - chmod 700 ~/.ssh
#     - ssh-keyscan $HOST_IP >> ~/.ssh/known_hosts
#     - chmod 644 ~/.ssh/known_hosts

#   script:
#     - ssh ubuntu@$HOST_IP "docker ps"
#     - scp clean.sh ubuntu@$HOST_IP:~
#     - ssh ubuntu@$HOST_IP "chmod +x clean.sh && ./clean.sh"
#     - ssh ubuntu@$HOST_IP "docker run --name it-delta-test -p 80:80 -d "$CI_REGISTRY_USER"/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHORT_SHA""
#     - ssh ubuntu@$HOST_IP "docker ps"

deploy-compose-job: 
  tags:
    - local
  stage: deploy-compose
  before_script:
    - 'command -v ssh-agent >/dev/null || ( apt-get update -y && apt-get install openssh-client -y )'
    - eval $(ssh-agent -s)
    - echo "$SSH_KEY" | tr -d '\r' | ssh-add -
    - mkdir -p ~/.ssh
    - chmod 700 ~/.ssh
    - ssh-keyscan $HOST_IP >> ~/.ssh/known_hosts
    - chmod 644 ~/.ssh/known_hosts

  script:
    - scp compose-clean.sh ubuntu@$HOST_IP:~
    - ssh ubuntu@$HOST_IP "chmod +x compose-clean.sh && ./compose-clean.sh"
    - ssh ubuntu@$HOST_IP "./compose-clean.sh" 
    - scp docker-compose.yaml ubuntu@$HOST_IP:~
    - ssh ubuntu@$HOST_IP "sed -i 's|MY_EMAIL_LETSENCRIPT|"$CI_EMAIL_LETSENCRIPT"|g' docker-compose.yaml"
    - ssh ubuntu@$HOST_IP "sed -i 's|MY_IMAGE|"$CI_REGISTRY_USER"/"$CI_REGISTRY_IMAGE":"$CI_COMMIT_SHORT_SHA"|g' docker-compose.yaml"
    - ssh ubuntu@$HOST_IP "sed -i 's|MY_HOSTNAME|"$CI_HOSTNAME"|g' docker-compose.yaml"   
    - ssh ubuntu@$HOST_IP "docker-compose up -d"
